package sunlight.util.config;

import java.io.IOException;
import java.net.URL;
import java.security.Provider;
import java.util.InvalidPropertiesFormatException;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import sunlight.criptography.Cryptographer;

public class EncryptedRemoteConfigurationFile extends RemoteConfigurationFile {
	
	private String 		  Algorithm;
	private Cryptographer Encryptor ;
	
	
	public EncryptedRemoteConfigurationFile(){
		super();
	}
	
	public EncryptedRemoteConfigurationFile(URL path){
		super(path);
	}
	
	public EncryptedRemoteConfigurationFile(URL path, int type) throws InvalidPropertiesFormatException, IOException{
		super(path, type);
	}
	
	public EncryptedRemoteConfigurationFile(URL path, int type, String key) throws InvalidPropertiesFormatException, IOException{
		super(path, type);
		
		this.Encryptor = new Cryptographer(new BouncyCastleProvider(), key);
	}
	
	public EncryptedRemoteConfigurationFile(URL path, int type, Provider JCEProvider) throws InvalidPropertiesFormatException, IOException{
		super(path, type);
		
		this.Encryptor = new Cryptographer(JCEProvider);
	}
	
	public EncryptedRemoteConfigurationFile(URL path, int type, Provider JCEProvider, String key) throws InvalidPropertiesFormatException, IOException{
		super(path, type);
		
		this.Encryptor = new Cryptographer(JCEProvider, key);
	}
	
	public EncryptedRemoteConfigurationFile(URL path, int type, Provider JCEProvider, String key, String algorithm) throws InvalidPropertiesFormatException, IOException{
		super(path, type);
		
		this.Algorithm = algorithm;
		
		this.Encryptor = new Cryptographer(JCEProvider, key, algorithm);
	}
	
	public EncryptedRemoteConfigurationFile(URL path, int type, String key, String algorithm) throws InvalidPropertiesFormatException, IOException{
		super(path, type);
		
		this.Algorithm = algorithm;
		
		this.Encryptor = new Cryptographer(new BouncyCastleProvider(), key, algorithm);
	}
	
	public void setKey(String key){
		this.Encryptor.setKey(key);
	}
	
	public void setAlgorithm(String algorithm){
		this.Encryptor.setAlgorithm(algorithm);
	}
	
	public Object get(String key){
		Object raw = this.Handler.get(key);
		if(raw != null){//decripteaza string-ul;
			String encrypted = raw.toString();
			
			return this.Encryptor.decrypt(encrypted);
		}
		
		return null;
	}
	
	public Object get(String key, String defaultvalue){
		Object raw = this.Handler.get(key);
		if(raw != null){//decripteaza string-ul;
			String encrypted = raw.toString();
			
			return this.Encryptor.decrypt(encrypted);
		}
		
		return defaultvalue;
	}
	
	public String getAlgorithm(){
		return this.Algorithm;
	}
}
